<template>
	<view class="container">
		<!-- 顶部栏 -->
		<view class="header">
			<!-- <text class="back" @tap="goBack">←</text>
			 -->
		
			<picker mode="selector" :range="projects" range-key="text" @change="onProjectSelect">
				<view class="title-box">
					<text class="project-title">{{ currentProject.text || '请选择项目' }}</text>
					<text class="dropdown">▼</text>
				</view>
			</picker>
			<text class="add" @tap="onAdd">创建项目</text>
			<!-- <image :src="project.icon" class="project-icon" /> -->
		</view>

		<!-- 成员和设备信息 -->
		<text class="sub-info">{{ project.members.length }}个成员 ｜ {{ project.devices }}个监测设备</text>

		<!-- 成员列表 -->
		<view class="card">
			<view class="member" v-for="(member, index) in project.members" :key="index" @tap="openMember(member)">
				<image class="avatar" :src="member.avatar?member.avatar:'https://yun.qiongtuyule.com/static/img/login/logo.png'" />
				<view class="info">
					<text class="name">{{ member.name }}</text>
					<text class="role">{{ member.role }}</text>
				</view>
				<text class="arrow">></text>
			</view>
			<view class="member invite" @tap="showInvitePopup">
				<view class="invite-avatar">＋</view>
				<text class="invite-text">邀请成员</text>
			</view>
		</view>

		<!-- 设置项 -->
		<view class="card">
			<view class="row" @tap="editName">
				<text>项目名称</text>
				<view class="right">
					<text class="light">{{ project.name }}</text>
					<m-icon type="arrowright" size="18" color="#bbb" class="my-menu-arrow"></m-icon>

				</view>
			</view>
			<view class="row" @tap="editIcon">
				<text>项目图标</text>
				<m-icon type="arrowright" size="18" color="#bbb" class="my-menu-arrow"></m-icon>

			</view>
			<view class="row">
				<text>项目区域</text>
				<view class="right" @tap="showRegionPopup()">
					<text class="light">{{ project.region }}</text>
					<m-icon type="arrowright" size="18" color="#bbb" class="my-menu-arrow"></m-icon>

				</view>
			</view>
			<view class="row" @tap="manageDevices">
				<text>设备管理</text>
				<view class="right">
					<text class="light">{{ project.devices }}</text>
					<m-icon type="arrowright" size="18" color="#bbb" class="my-menu-arrow"></m-icon>

				</view>
			</view>
		</view>

		<!-- 新建项目弹窗 -->
		<view class="modal-mask" v-if="createModal">
			<view class="modal-box">
				<view class="modal-title">创建项目</view>

				<input class="modal-input" type="text" placeholder="请输入项目名称" v-model="form.name" />

				<input class="modal-input" type="number" placeholder="请输入项目排序" v-model="form.order" />

				<!-- 上传图标 -->
				<!-- 				<view class="upload-wrapper" @tap="chooseImage">
							<image v-if="form.icon" :src="form.icon" class="upload-icon-preview" mode="aspectFill" />
							<view v-else class="upload-box">
								<text class="plus">＋</text>
								<text class="upload-text">上传图标</text>
							</view>
						</view> -->
				<!-- 上传图标 -->
				<fileUploader :limitsize="10240" :maxcount="1" @get-img="getImg" v-if="createModal"></fileUploader>

				<!-- 底部按钮 -->
				<view class="modal-footer">
					<button class="cancel-btn" @tap="closeModal">取消</button>
					<button class="confirm-btn" @tap="submitForm">确定</button>
				</view>
			</view>
		</view>

		<!-- 邀请成员弹窗 -->
		<uni-popup ref="invitePopup" type="center">
			<view class="popup">
				<text class="popup-title">邀请成员</text>

				<input class="popup-input" v-model="inviteForm.username" placeholder="请输入登录账号" />
				<input class="popup-input" v-model="inviteForm.password" placeholder="请输入登录密码" password />
				<input class="popup-input" v-model="inviteForm.name" placeholder="请输入成员姓名" />
				<picker :range="[project.name]" @change="onProjectChange">
					<view class="popup-input">{{ project.name }} ▼</view>
				</picker>
				<input class="popup-input" v-model="inviteForm.position" placeholder="请输入成员职务" />
				<input class="popup-input" v-model="inviteForm.phone" placeholder="请输入成员手机号" />

				<view class="popup-buttons">
					<button class="cancel-btn" @tap="hideInvitePopup">取消</button>
					<button class="confirm-btn" @tap="submitInvite">确定</button>
				</view>
			</view>
		</uni-popup>
		<!-- 区域管理弹窗 -->
		<uni-popup ref="regionPopup" type="center">
			<view class="popup">
				<text class="popup-title">区域管理</text>

				<!-- 单选按钮：修改/新建 -->
				<view class="radio-row">
					<label @tap="regionForm.mode = 'edit'">
						<radio :checked="regionForm.mode === 'edit'" color="#000" />
						<text class="radio-label">修改区域</text>
					</label>
					<label @tap="regionForm.mode = 'create'">
						<radio :checked="regionForm.mode === 'create'" color="#000" />
						<text class="radio-label">新建区域</text>
					</label>
				</view>

				<!-- 上级区域选择 -->
				<picker :range="parentRegions" :range-key="'name'" @change="onParentRegionChange">
					<view class="popup-input">
						{{ regionForm.parentName || '请选择上级区域' }} ▼
					</view>
				</picker>

				<!-- 仅在修改模式下显示子区域选择 -->
				<picker v-if="regionForm.mode === 'edit'" :range="childRegions" :range-key="'name'"
					@change="onChildRegionChange">
					<view class="popup-input">{{ regionForm.name || '请选择下级区域' }} ▼</view>
				</picker>

				<!-- 区域名称输入 -->
				<!-- <input class="popup-input" v-model="regionForm.name" placeholder="请输入区域名称" /> -->

				<!-- 仅在新建模式下显示输入框 -->
				<input v-if="regionForm.mode === 'create'" class="popup-input" v-model="regionForm.name"
					placeholder="请输入区域名称" />

				<!-- 操作按钮 -->
				<view class="popup-buttons">
					<button class="cancel-btn" @tap="hideRegionPopup">取消</button>
					<button class="confirm-btn" @tap="submitRegion">确定</button>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="editNamePopup" type="center">
			<view class="popup">
				<text class="popup-title">修改项目名称</text>
				<input class="popup-input" v-model="editNameForm.name" />
				<view class="popup-buttons">
					<button class="cancel-btn" @tap="hideEditNamePopup">取消</button>
					<button class="confirm-btn" @tap="submitEditName">确定</button>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="editIconPopup" type="center">
			<view class="popup">
				<text class="popup-title">修改图标</text>
				<fileUploader :limitsize="10240" :maxcount="1" @get-img="getImg" v-if="showModal"></fileUploader>
				<view class="popup-buttons">
					<button class="cancel-btn" @tap="hideEditIconPopup">取消</button>
					<button class="confirm-btn" @tap="submitEditIcon">确定</button>
				</view>
			</view>
		</uni-popup>



	</view>
</template>

<script>
	export default {
		data() {
			return {
				projects: [], // 项目列表
				currentProject: {}, // 当前选中
				projectId: null,
				project: {
					name: "",
					region: "",
					devices: 0,
					members: [
						// {
						// 	name: "灵魂摆渡人(我)",
						// 	role: "项目创建者"
						// },
						// {
						// 	name: "我是喵咪",
						// 	role: "成员"
						// }
					],
				},
				editNameForm: {
					name: ''
				},
				editIconForm: {
					url: ''
				},
				showModal: true,
				regionForm: {
					mode: 'create', // 'create' 或 'edit'
					parentId: null,
					parentName: '',
					name: ''
				},
				regionList: [],
				parentRegions: [], // 顶级区域（pid === 0） 示例上级区域名称（实际应来自接口）
				childRegions: [], // 当前选中上级区域的下级区域
				inviteForm: {
					username: "",
					password: "",
					name: "",
					project: "",
					position: "",
					phone: ""
				},
				form: {
					name: '',
					order: '',
					icon: ''
				},
				createModal: false
			};
		},
		onLoad(options) {
			this.projectId = options.project_id;
			this.fetchProjectDetail();
			this.fetchRegionList();
			this.getSiteList(); // 加载项目列表
		},
		methods: {
			closeCreateModal() {
				this.createModal = false;
			},
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.form.icon = res.tempFilePaths[0];
					}
				});
			},
			async submitForm() {
				if (!this.form.name) {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					});
					return;
				}

				const res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.projectCreate,
					data: {
						name: this.form.name,
						order: this.form.order,
						icon: this.form.icon
					},
					needLogin: true
				});

				if (res.code === 1) {
					uni.showToast({
						title: '创建成功',
						icon: 'success'
					});
					this.closeCreateModal();
					this.getSiteList();
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			},
			closeModal() {
				this.createModal = false;
			},
			getImg(data) {
				this.form.icon = data[0];
			},
			onAdd() {
				// 重置表单内容
				this.form = {
					name: '',
					order: '',
					icon: ''
				};
				// 显示弹窗
				this.createModal = true;
			},
			async getSiteList() {
				let res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.siteTree2,
					data: {
						page: 1,
						limit: 100
					}
				})
				if (res.code == 1) {
					this.projects = res.data
					console.log(this.projects)
					if (this.projectId && this.projects) {
						console.log("Project ID:", this.projectId); // 打印 projectId
						console.log("Project ID type:", typeof this.projectId); // 打印 projectId 类型

						// 确保 projectId 是数字类型（如果需要）
						const projectId = parseInt(this.projectId, 10);

						// 使用 filter 方法查找匹配的项目
						const matchedProjects = this.projects.filter(item => item.value === projectId);

						console.log("Matched projects:", matchedProjects); // 打印匹配结果

						if (matchedProjects.length > 0) {
							// 如果找到匹配的项目，赋值给 currentProject
							this.currentProject = matchedProjects[0];
							console.log("Current project:", this.currentProject); // 打印当前项目
						} else {
							// 如果没有找到匹配的项目，设置为 null 或默认值
							this.currentProject = null;
							console.log("没有找到匹配的项目");
						}
					}

				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			async onProjectSelect(e) {
				console.log(e)
				let index = e.detail.value;
				this.currentProject = this.projects[index];
				console.log(this.projects[index])
				this.projectId = this.projects[index].value
				this.fetchProjectDetail();
			},
			showEditNamePopup() {
				this.editNameForm.name = this.project.name;
				this.$refs.editNamePopup.open();
			},
			hideEditNamePopup() {
				this.$refs.editNamePopup.close();
			},
			showRegionPopup() {
				this.$refs.regionPopup.open();
			},
			hideRegionPopup() {
				this.$refs.regionPopup.close();
			},
			onParentRegionChange(e) {
				const index = e.detail.value;
				const parent = this.parentRegions[index];


				this.regionForm.parentId = parent.id;
				this.regionForm.parentName = parent.name;
				this.childRegions = this.regionList.filter(item => item.pid === parent.id);
				this.regionForm.name = '';
			},
			onChildRegionChange(e) {
				const index = e.detail.value;
				const child = this.childRegions[index];
				this.regionForm.name = child.name;
				this.regionForm.id = child.id; // 用于提交修改请求
			},
			async submitRegion() {
				// if (!this.regionForm.name || this.regionForm.parentId === null) {
				// 	return uni.showToast({
				// 		title: '请填写完整信息',
				// 		icon: 'none'
				// 	});
				// }

				// // 根据模式执行不同操作
				// const action = this.regionForm.mode === 'create' ? '新建' : '修改';
				// uni.showToast({
				// 	title: `${action}区域：${this.regionForm.name}`,
				// 	icon: 'success'
				// });

				// // 清空表单并关闭
				// this.regionForm = {
				// 	mode: 'create',
				// 	parentId: null,
				// 	parentName: '',
				// 	name: ''
				// };
				// this.hideRegionPopup();
				if (this.regionForm.mode === 'create') {
					if (!this.regionForm.parentId || !this.regionForm.name.trim()) {
						return uni.showToast({
							title: '请填写完整信息',
							icon: 'none'
						});
					}

					const res = await this.$lib.$http.post({
						url: this.$lib.$urlMap.createRegion,
						data: {
							name: this.regionForm.name,
							pid: this.regionForm.parentId,
							depart_id: this.projectId,
						},
						needLogin: true
					});
					if (res.code !== 1) {
						return uni.showToast({
							title: res.msg || '新建失败',
							icon: 'none'
						});
					}
					uni.showToast({
						title: '新建成功',
						icon: 'success'
					});
				} else {
					if (!this.regionForm.parentId || !this.regionForm.id || !this.regionForm.name.trim()) {
						return uni.showToast({
							title: '请选择完整区域',
							icon: 'none'
						});
					}
					const res = await this.$lib.$http.post({
						url: this.$lib.$urlMap.updateRegion,
						data: {
							id: this.regionForm.id,
							name: this.regionForm.name,
							depart_id: this.projectId
						},
						needLogin: true
					});
					if (res.code !== 1) {
						return uni.showToast({
							title: res.msg || '修改失败',
							icon: 'none'
						});
					}
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
				}

				this.regionForm = {
					mode: 'create',
					parentId: null,
					parentName: '',
					name: '',
					id: null
				};
				this.hideRegionPopup();
				this.fetchRegionList();
			},
			goBack() {
				uni.navigateBack();
			},
			openMember(member) {
				uni.showToast({
					title: `点击成员：${member.name}`,
					icon: "none"
				});
			},
			async submitEditName() {
				if (!this.editNameForm.name.trim()) {
					return uni.showToast({
						title: '请输入项目名称',
						icon: 'none'
					});
				}
				const res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.updateProjectName,
					data: {
						project_id: this.projectId,
						name: this.editNameForm.name
					},
					needLogin: true
				});
				if (res.code === 1) {
					this.project.name = this.editNameForm.name;
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
					this.hideEditNamePopup();
				} else {
					uni.showToast({
						title: res.msg || '修改失败',
						icon: 'none'
					});
				}
			},
			editName() {
				this.showEditNamePopup();
			},
			getImg(data) {
				this.editIconForm.url = data[0]; // fileUploader 返回的本地路径
			},
			showEditIconPopup() {
				this.editIconForm.url = '';
				this.$refs.editIconPopup.open();
				// this.showModal = true;
			},
			hideEditIconPopup() {
				this.$refs.editIconPopup.close();
				// this.showModal = false;
			},
			editIcon() {
				this.showEditIconPopup();
			},
			async submitEditIcon() {
				if (!this.editIconForm.url) {
					return uni.showToast({
						title: '请先上传图标',
						icon: 'none'
					});
				}
				const uploadRes = await this.$lib.$http.post({
					url: this.$lib.$urlMap.uploadProjectIcon,
					data: {
						id: this.projectId,
						icon: this.editIconForm.url // 这里是字符串，不是文件路径
					},
					needLogin: true
				});
				if (uploadRes.code === 1) {
					// this.project.icon = uploadRes.data.url;
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
					this.hideEditIconPopup();
				} else {
					uni.showToast({
						title: uploadRes.msg || '上传失败',
						icon: 'none'
					});
				}
			},
			editRegion() {
				// uni.showToast({
				// 	title: "编辑区域功能开发中",
				// 	icon: "none"
				// });
			},
			manageDevices() {
				uni.navigateTo({
					url: `/pages/xunjian/project?id=${this.projectId}`,
				});
			},
			showInvitePopup() {
				this.$refs.invitePopup.open();
			},
			hideInvitePopup() {
				this.$refs.invitePopup.close();
			},
			onProjectChange(e) {
				this.inviteForm.project = this.project.name;
			},
			async submitInvite() {
				const data = {
					username: this.inviteForm.username,
					password: this.inviteForm.password,
					name: this.inviteForm.name,
					depart_id: this.projectId,
					position: this.inviteForm.position,
					phone: this.inviteForm.phone
				};

				if (!data.username || !data.password || !data.name) {
					return uni.showToast({
						title: "请填写完整信息",
						icon: "none"
					});
				}

				const res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.inviteMember,
					data,
					needLogin: true
				});

				if (res.code === 1) {
					uni.showToast({
						title: "邀请成功",
						icon: "success"
					});
					this.hideInvitePopup();
					this.fetchProjectDetail(); // 重新加载项目成员列表
				} else {
					uni.showToast({
						title: res.msg || "邀请失败",
						icon: "none"
					});
				}
			},
			async fetchProjectDetail() {
				const res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.getProjectDetail,
					data: {
						project_id: this.projectId
					},
					needLogin: true
				});

				if (res.data && res.code === 1) {
					this.project = res.data;
				} else {
					uni.showToast({
						title: res.msg || '获取项目信息失败',
						icon: 'none'
					});
				}
			},
			async fetchRegionList() {
				const res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.getRegionList,
					data: {},
					needLogin: true
				});
				if (res.code === 1) {
					this.regionList = res.data
					this.parentRegions = res.data.filter(item => item.pid === 0);
				} else {
					uni.showToast({
						title: res.msg || '区域加载失败',
						icon: 'none'
					});
				}
			}

		}
	};
</script>

<style>
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.modal-box {
		width: 600rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-sizing: border-box;
	}

	.modal-title {
		text-align: center;
		font-size: 34rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
	}

	.modal-input {
		background-color: #f7f7f7;
		height: 80rpx;
		border-radius: 12rpx;
		padding: 0 24rpx;
		margin-bottom: 24rpx;
		font-size: 28rpx;
	}

	.upload-wrapper {
		margin: 20rpx 0;
	}

	.upload-box {
		width: 120rpx;
		height: 120rpx;
		border: 1px solid #ccc;
		border-radius: 16rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.plus {
		font-size: 48rpx;
		color: #aaa;
	}

	.upload-text {
		font-size: 22rpx;
		color: #aaa;
		margin-top: 8rpx;
	}

	.upload-icon-preview {
		width: 120rpx;
		height: 120rpx;
		border-radius: 16rpx;
	}

	.modal-footer {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #000;
		flex: 1;
		margin-right: 20rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 12rpx;
	}

	.confirm-btn {
		background-color: #000;
		color: #fff;
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 12rpx;
	}


	.radio-row {
		display: flex;
		justify-content: space-around;
		margin-bottom: 20rpx;
	}

	.radio-label {
		margin-left: 10rpx;
		font-size: 28rpx;
	}

	.popup {
		width: 600rpx;
		background-color: #fff;
		padding: 40rpx 30rpx;
		border-radius: 30rpx;
	}

	.popup-title {
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.popup-input {
		background-color: #f5f5f5;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		font-size: 28rpx;
	}

	.popup-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #000;
		flex: 1;
		margin-right: 20rpx;
		border-radius: 16rpx;
	}

	.confirm-btn {
		background-color: #000;
		color: #fff;
		flex: 1;
		border-radius: 16rpx;
	}

	.container {
		background: #f8f8f8;
		min-height: 100vh;
		padding: 20rpx;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
		/* margin-top: 20rpx; */
	}

	.back {
		font-size: 40rpx;
	}

	.title-box {
		display: flex;
		align-items: center;
	}

	.project-title {
		font-size: 34rpx;
		font-weight: bold;
	}

	.dropdown {
		font-size: 28rpx;
		margin-left: 10rpx;
	}

	.add {
		font-size: 30rpx;
	}

	.sub-info {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 20rpx;
	}

	.card {
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}

	.member {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.member:last-child {
		border-bottom: none;
	}

	.avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 30rpx;
		background: #eee;
		margin-right: 20rpx;
	}

	.info {
		flex: 1;
	}

	.name {
		font-weight: bold;
	}

	.role {
		font-size: 24rpx;
		color: #999;
		margin-left:5rpx;
	}

	.arrow {
		font-size: 28rpx;
		color: #ccc;
	}

	.invite {
		border-bottom: none;
	}

	.invite-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 30rpx;
		background: #f0f0f0;
		text-align: center;
		line-height: 60rpx;
		font-size: 36rpx;
		color: #aaa;
		margin-right: 20rpx;
	}

	.invite-text {
		color: #666;
	}

	.row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 1px solid #eee;
	}

	.right {
		display: flex;
		align-items: center;
		color: #999;
	}

	.light {
		margin-right: 10rpx;
	}

	/* .project-icon {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	} */
</style>